# coding: utf-8
import os
import time
import random
import matplotlib.pyplot as plt
from matplotlib import animation
import numpy as np
import cv2

file_path = './autojump.png'
chess = cv2.imread('./character.png')
need_update = True
pic_index = 0

def get_pic_path(pic_index):
	return './pic/{}.png'.format(pic_index)

def get_chess_pos():
	im = cv2.imread(get_pic_path(pic_index))
	_, score, _, pos = cv2.minMaxLoc(cv2.matchTemplate(im, chess, cv2.TM_CCOEFF_NORMED))
	return pos[0] + 40, pos[1] + 195

def on_click(event):
	global need_update, pic_index
	x0, y0 = get_chess_pos()
	x1, y1 = event.xdata, event.ydata
	distance = ((x1-x0)**2 + (y1-y0)**2)**0.5
	press_time = int(distance * 1.35)
	press_x, press_y = random.randint(10, 1080), random.randint(500, 1500)
	cmd = 'adb shell input swipe {} {} {} {} {}'.format(press_x, press_y, press_x, press_y, press_time)
	os.system(cmd)
	need_update = True
	pic_index += 1

def get_date():
	os.system('adb shell screencap -p /sdcard/autojump.png')
	os.system('adb pull /sdcard/autojump.png {}'.format(get_pic_path(pic_index)))

	data = cv2.imread(get_pic_path(pic_index))
	return np.array(cv2.cvtColor(data, cv2.COLOR_BGR2RGBA))

figure = plt.figure()
im = plt.imshow(get_date(), animated=True)
figure.canvas.mpl_connect('button_press_event', on_click)

def animate(i):
	global need_update
	if need_update:
		time.sleep(1.2)
		im.set_array(get_date())
		need_update = False
	return im,

anim = animation.FuncAnimation(figure, animate, interval=50, blit=True)
plt.show()



